package org.traffometer.traffosim;

import java.io.File;

/**
 * Provides a command line user interface.
 * 
 * @author Nam Nguyen
 */
public class CommandLineUi extends UserInterface {
  
  /** Controller implements the simulation functionality. */
  protected Controller controller;
  
  /**
   * Specifies if there is a need to print out the packets or not. 
   */
  private final boolean list;
  
  /**
   * Indicates whether a configuration file was successfully found.
   */
  private final boolean fileAvailable;
  
  /** Error message if the server address is missing. */
  static final String missingServerErrorMsg = "No server address given.";
  /** Error message if the config file is missing. */
  static final String missingConfigErrorMsg = "No config file given.";
 
  /**
   * Required Constructor.
   * 
   * @param args command line arguments
   * @throws ConfigException If there are errors with configuration file.
   */
  public CommandLineUi (String[] args) throws ConfigException {
    super(args);
    
    boolean serverAvailable = false;
    boolean list = false;
    boolean fileAvailable = false;
    
    // create controller
    controller = new Controller();
    
    // parse command line args
    for (int i = 0; i < args.length; i++) {
        if ("-server".equals(args[i])) {
          controller.setServerAddress(args[i + 1]);
          serverAvailable = true;
        }
        else if ("-config".equals(args[i])) {
          File configFile = new File(args[i + 1]);
          if (configFile.isFile()) {
            controller.openConfig(configFile);
            fileAvailable = true;
          }
          else {
            System.err.println("Specified config file does not exist");
          }
        }
        else if ("-list".equals(args[i])) {
          list = true;
        }
    }    
    
    this.list = list;
    this.fileAvailable = fileAvailable;
    
    if (!serverAvailable && !this.list) {
      System.err.println(missingServerErrorMsg);
    }
    
    if (!this.fileAvailable) {
      System.err.println(missingConfigErrorMsg);
    }
  }
  
  /**
   * Prints the packets to the screen if "-list" argument was given.
   * Sends the packets otherwise.
   */
  public void start() {
    if (!this.fileAvailable) {
      System.err.println("No config file, nothing to do.");
      return;
    }
    // print packets if "-list" is found in arguments list
    if (list) {
      controller.printPackets(); 
    }
  }
}
